package com.sc.web.quartz;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.dal.model.ParamMap;
import com.sc.dal.model.base.BaseSku;
import com.sc.dal.model.base.BaseSkuValue;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsBrand;
import com.sc.dal.model.goods.GoodsClass;
import com.sc.dal.model.goods.GoodsSku;
import com.sc.dal.model.goods.GoodsStock;
import com.sc.dal.model.order.OrderPayment;
import com.sc.dal.model.order.Orders;
import com.sc.dal.model.order.Products;
import com.sc.service.base.BaseSkuService;
import com.sc.service.base.BaseSkuValueService;
import com.sc.service.goods.GoodsBrandService;
import com.sc.service.goods.GoodsClassService;
import com.sc.service.goods.GoodsService;
import com.sc.service.goods.GoodsSkuService;
import com.sc.service.goods.GoodsStockService;
import com.sc.service.order.OrderService;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DateUtil;
import com.sc.util.openAPI.OpenAPI;
import com.sc.util.spring.SpringUtils;


public class GoodsJob {
	@Autowired
	private OrderService orderService;
	
	//private boolean isLogin = false;
	
	OpenAPI api = new OpenAPI(ConfigBeanAdapter.t_srvUrl,ConfigBeanAdapter.t_appKey,ConfigBeanAdapter.t_appSecret,ConfigBeanAdapter.t_user,ConfigBeanAdapter.t_pwd,ConfigBeanAdapter.t_account);
	
	
	/**
	 * 登录
	 * @return OpenAPI
	 */
	/*private OpenAPI login(){
		OpenAPI api = new OpenAPI(srvUrl, appKey, appSecret);
		try{
			//由于T+登录在这有问题，所以这里的逻辑踩用，先登录，再重新登录，并修改了setJson的代码
			api.Login(user, pwd, account);
			api.get("Authorization/ReLogin");//重新登录方法
			return api;
		}catch(Exception e){
			e.printStackTrace();
			return api;
		}
	}*/
	
	/**
	 * 查询T+存货信息
	 * 返回信息：{"code":"EXSM0003","message":"提供令牌信息不正确"}
	 */
	public void getTPlusGoods() {
		//查询所有的存货数据
		String method = "inventory/Query";
		String data = "{param:{SelectFields:\"Id,Code,Name,Shorthand,Specification,DefaultBarCode,RetailPriceNew,InventoryClass.Id,Unit.Id,Unit.Code,Productinfo.Id,LatestCost,ImageList,Disabled\"}}";
		
		String jsonstr;
		try {
			GoodsService goodsService = (GoodsService)SpringUtils.getBean("goodsService");	//获取商品服务对象
			
			//登录
			//OpenAPI api = login();
			
			//获取数据
			jsonstr = api.getData(method, data);
			
			JSONArray jsonArray = JSONArray.parseArray(jsonstr);
			for(Object object : jsonArray){
				JSONObject jsonObject = (JSONObject)object;
				
				//构建商品数据对象
				Goods goods = new Goods();
				goods.setId(jsonObject.getInteger("Id"));
				goods.setCode(jsonObject.getString("Code"));
				goods.setName(jsonObject.getString("Name"));
				goods.setShorthand(jsonObject.getString("Shorthand"));
				goods.setSpecification(jsonObject.getString("Specification"));
				goods.setDefaultBarCode(jsonObject.getString("DefaultBarCode"));
				goods.setMarketPrice(jsonObject.getBigDecimal("RetailPriceNew"));	//获取存货的零售价
				goods.setIsDelete("true".equals(jsonObject.getString("Disabled"))?"1":"0");
				if(StringUtils.isNotBlank(jsonObject.getString("LatestCost"))){
					goods.setCostPrice(jsonObject.getBigDecimal("LatestCost").setScale(2,BigDecimal.ROUND_HALF_UP));
				}
				
				//分类
				if(StringUtils.isNotBlank(jsonObject.getString("InventoryClass"))){
					JSONObject jsonObjectClass = (JSONObject)JSONObject.parse(jsonObject.getString("InventoryClass"));
					goods.setClassId(jsonObjectClass.getString("Id"));
				}
				//单位
				if(StringUtils.isNotBlank(jsonObject.getString("Unit"))){
					JSONObject jsonObjectUnit = (JSONObject)JSONObject.parse(jsonObject.getString("Unit"));
					goods.setUnit(jsonObjectUnit.getString("Id"));
				}
				//品牌
				if(StringUtils.isNotBlank(jsonObject.getString("Productinfo"))){
					JSONObject jsonObjectBrand = (JSONObject)JSONObject.parse(jsonObject.getString("Productinfo"));
					goods.setBrand(jsonObjectBrand.getString("Id"));
				}
				//图片
				if(StringUtils.isNotBlank(jsonObject.getString("ImageList"))){
					JSONArray jsonArrayImage = JSONArray.parseArray(jsonObject.getString("ImageList"));
					if(jsonArrayImage.size()>0){
						StringBuilder imageUrlSb = new StringBuilder();
						for(Object objectImage : jsonArrayImage){
							JSONObject jsonObjectImage = (JSONObject)objectImage;
							String imageUrl = jsonObjectImage.getString("ImageUrl");
							
							imageUrlSb.append(imageUrl).append(",");
							
							if(jsonObjectImage.getBoolean("IsDefault")){
								goods.setPicture(imageUrl);
							}
						}
						
						goods.setImageFile(imageUrlSb.substring(0, imageUrlSb.length()-1));
					}
				}
				
				goods.setTitle(jsonObject.getString("Name"));
				goods.setKeywords(jsonObject.getString("Name"));
				goods.setDescript(jsonObject.getString("Name"));
				
				//先查询是否存在此条商品数据
				Goods goodsOld = goodsService.selectOneGoods(goods.getId());
				if(goodsOld==null){
					goods.setCreater("零售主管");
					goods.setModifier("零售主管");
					goods.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
					goods.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					goodsService.insertOneGoods(goods);
				}else{
					goods.setModifier("零售主管");
					goods.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					goodsService.updateOneGoods(goods);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	/**
	 * 查询T+品牌信息
	 * 返回信息：{"code":"EXSM0003","message":"提供令牌信息不正确"}
	 */
	public void getTPlusBrand() {
		//查询所有的品牌数据
		String method = "brand/Query";
		String data = "{param:{SelectFields:\"Id,Code,Name\"}}";
		
		String jsonstr;
		
		try {
			GoodsBrandService goodsBrandService = (GoodsBrandService)SpringUtils.getBean("goodsBrandService");	//获取品牌服务对象
			
			//登录
			//OpenAPI api = login();
			
			//获取数据
			jsonstr = api.getData(method, data);
			
			JSONArray jsonArray = JSONArray.parseArray(jsonstr);
			for(Object object : jsonArray){
				JSONObject jsonObject = (JSONObject)object;
				
				//构建品牌数据对象
				GoodsBrand goodsBrand = new GoodsBrand();
				goodsBrand.setId(jsonObject.getInteger("Id"));
				goodsBrand.setCode(jsonObject.getString("Code"));
				goodsBrand.setName(jsonObject.getString("Name"));
				goodsBrand.setIsDelete("0");
				
				//先查询是否存在此条品牌数据
				GoodsBrand goodsBrandOld = goodsBrandService.selectByPrimaryKey(goodsBrand.getId());
				
				if(goodsBrandOld==null){
					goodsBrand.setCreater("零售主管");
					goodsBrand.setModifier("零售主管");
					goodsBrand.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
					goodsBrand.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					
					goodsBrandService.insert(goodsBrand);
				}else{
					goodsBrand.setModifier("零售主管");
					goodsBrand.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					
					goodsBrandService.update(goodsBrand);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询T+分类信息
	 * 返回信息：{"code":"EXSM0003","message":"提供令牌信息不正确"}
	 */
	public void getTPlusClass() {
		//查询所有的分类数据
		String method = "inventoryClass/Query";
		String data = "{param:{SelectFields:\"Id,Code,Name,ParentCode,IsEndNode,Depth\"}}";
		
		String jsonstr;
		
		try {
			GoodsClassService goodsClassService = (GoodsClassService)SpringUtils.getBean("goodsClassService");	//获取分类服务对象
			
			//登录
			//OpenAPI api = login();
			
			//获取数据
			jsonstr = api.getData(method, data);
			
			JSONArray jsonArray = JSONArray.parseArray(jsonstr);
			for(Object object : jsonArray){
				JSONObject jsonObject = (JSONObject)object;
				
				//构建分类数据对象
				GoodsClass goodsClass = new GoodsClass();
				goodsClass.setId(jsonObject.getInteger("Id"));
				goodsClass.setCode(jsonObject.getString("Code"));
				goodsClass.setName(jsonObject.getString("Name"));
				goodsClass.setIsDelete("0");
				String parentCode = jsonObject.getString("ParentCode");
				if(StringUtils.isNotBlank(parentCode)){
					String dataOne = "{param:{Code:\""+parentCode+"\",SelectFields:\"Id,Code,Name,ParentCode\"}}";
					jsonstr = api.getData(method, dataOne);
					
					JSONArray jsonArrayClass = JSONArray.parseArray(jsonstr);
					if(jsonArrayClass.size()>0){
						JSONObject jsonObjectOne = (JSONObject)jsonArrayClass.get(0);
						goodsClass.setParentId(Integer.valueOf(jsonObjectOne.getString("Id")));
					}
				}
				goodsClass.setIsEndNode(Boolean.valueOf(jsonObject.getString("IsEndNode"))?"1":"0");
				goodsClass.setDepth(jsonObject.getByte("Depth"));
				
				
				//先查询是否存在此条分类数据
				GoodsClass goodsClassOld = goodsClassService.selectByPrimaryKey(goodsClass.getId());
				
				if(goodsClassOld==null){
					goodsClass.setCreater("零售主管");
					goodsClass.setModifier("零售主管");
					goodsClass.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
					goodsClass.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					
					goodsClassService.insertGoodsClass(goodsClass);
				}else{
					goodsClass.setModifier("零售主管");
					goodsClass.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					
					goodsClassService.updateGoodsClass(goodsClass);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询T+基本规格信息
	 * 返回信息：{"code":"EXSM0003","message":"提供令牌信息不正确"}
	 */
	public void getTPlusBaseSku(){
		//查询所有的存货数据
		String method = "freeItemType/Query";
		String data = "{param:{}}";
		
		String methodFreeItem = "freeItem/Query";
		
		String jsonstr;
		
		try {
			BaseSkuService baseSkuService = (BaseSkuService)SpringUtils.getBean("baseSkuService");	//获取基本规格服务对象
			BaseSkuValueService baseSkuValueService = (BaseSkuValueService)SpringUtils.getBean("baseSkuValueService");	//获取基本规格服务对象
			
			//登录
			//OpenAPI api = login();
			
			//获取数据
			jsonstr = api.getData(method, data);
			
			JSONArray jsonArray = JSONArray.parseArray(jsonstr);
			for(Object object : jsonArray){
				JSONObject jsonObject = (JSONObject)object;
				
				//构建基本规格数据对象
				BaseSku baseSku = new BaseSku();
				baseSku.setId(jsonObject.getInteger("ID"));
				baseSku.setName(jsonObject.getString("Title"));
				baseSku.setIsDelete("0");
				
				//先查询是否存在此条基本规格数据
				BaseSku baseSkuOld = baseSkuService.selectByPrimaryKey(baseSku.getId());
				
				if(baseSkuOld==null){
					baseSku.setCreater("零售主管");
					baseSku.setModifier("零售主管");
					baseSku.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
					baseSku.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					baseSkuService.insert(baseSku);
					
				}else{
					baseSku.setModifier("零售主管");
					baseSku.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					baseSkuService.updateByPrimaryKey(baseSku);
				}
				
				//处理商品规格值数据
				String dataFreeItem = "{param:{type:\""+baseSku.getName()+"\",SelectFields:\"Id,Type,Code,Name\"}}";
				
				jsonstr = api.getData(methodFreeItem, dataFreeItem);
				JSONArray jsonArrayFreeItem = JSONArray.parseArray(jsonstr);
				for(Object objectFreeItem : jsonArrayFreeItem){
					JSONObject jsonObjectFreeItem = (JSONObject)objectFreeItem;
				
					//构建基本规格值数据对象
					BaseSkuValue baseSkuValue = new BaseSkuValue();
					baseSkuValue.setId(jsonObjectFreeItem.getInteger("Id"));
					baseSkuValue.setCode(jsonObjectFreeItem.getString("Code"));
					baseSkuValue.setName(jsonObjectFreeItem.getString("Name"));
					baseSkuValue.setSkuId(baseSku.getId());
					baseSkuValue.setIsDelete("0");
					
					BaseSkuValue baseSkuValueOld = baseSkuValueService.selectByPrimaryKey(baseSkuValue.getId());
					
					if(baseSkuValueOld==null){
						baseSkuValue.setCreater("零售主管");
						baseSkuValue.setModifier("零售主管");
						baseSkuValue.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
						baseSkuValue.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
						baseSkuValueService.insert(baseSkuValue);
					}else{
						baseSkuValue.setModifier("零售主管");
						baseSkuValue.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
						baseSkuValueService.updateByPrimaryKey(baseSkuValue);
					}
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询T+商品库存信息
	 * 返回信息：{"code":"EXSM0003","message":"提供令牌信息不正确"}
	 */
	public void getTPlusGoodsStock(){
		//查询所有的存货数据
		String method = "currentStock/Query";
		String data = "{param:{GroupInfo:{Warehouse:false,Inventory:true,InvProperty:true}}}";
		
		String jsonstr;
		
		try {
			GoodsStockService goodsStockService = (GoodsStockService)SpringUtils.getBean("goodsStockService");	//获取商品库存服务对象
			
			//登录
			//OpenAPI api = login();
			
			//获取数据
			jsonstr = api.getData(method, data);
			
			JSONArray jsonArray = JSONArray.parseArray(jsonstr);
			for(Object object : jsonArray){
				JSONObject jsonObject = (JSONObject)object;
				
				//构建分类数据对象
				GoodsStock goodsStock = new GoodsStock();
				goodsStock.setBaseQuantity(Integer.valueOf(jsonObject.getBigDecimal("ExistingQuantity").setScale(0,BigDecimal.ROUND_CEILING).toString()));
				
				//获取商品id
				String methodGoods = "inventory/Query";
				String dataGoods = "{param:{Code:\""+jsonObject.getString("InventoryCode")+"\",SelectFields:\"Id\"}}";
				//获取商品数据
				jsonstr = api.getData(methodGoods, dataGoods);
				JSONArray jsonArrayGoods = JSONArray.parseArray(jsonstr);
				if(jsonArrayGoods.size()>0){
					JSONObject jsonObjectGoods = (JSONObject)jsonArrayGoods.get(0);
					goodsStock.setGoodsId(jsonObjectGoods.getInteger("Id"));
				}
				
				//获取商品的库存规格（自由项）
				JSONArray jsonArrayFreeType = jsonObject.getJSONArray("DynamicPropertyKeys");
				JSONArray jsonArrayFreeTypeValue = jsonObject.getJSONArray("DynamicPropertyValues");
				for(Object objectFreeType : jsonArrayFreeType){
					String freeType = objectFreeType.toString();
					if("freeitem0".equals(freeType)){
						goodsStock.setFreeItem0(jsonArrayFreeTypeValue.get(0).toString());
						continue;
					}
					if("freeitem1".equals(freeType)){
						goodsStock.setFreeItem1(jsonArrayFreeTypeValue.get(1).toString());
						continue;
					}
					if("freeitem2".equals(freeType)){
						goodsStock.setFreeItem2(jsonArrayFreeTypeValue.get(2).toString());
						continue;
					}
					if("freeitem3".equals(freeType)){
						goodsStock.setFreeItem3(jsonArrayFreeTypeValue.get(3).toString());
						continue;
					}
				}
				
				//判断商品库存数据是否存在
				GoodsStock goodsStockOld = goodsStockService.selectOne(goodsStock);
				
				if(goodsStockOld==null){
					goodsStock.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
					goodsStock.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					goodsStockService.insert(goodsStock);
				}else{
					goodsStock.setId(goodsStockOld.getId());
					goodsStock.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
					goodsStockService.updateByPrimaryKey(goodsStock);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 处理商品对应的规格数据
	 * @param freeTypeValue
	 * @param goodsId
	 */
	private void handleGoodsSku(String freeTypeValue,Integer goodsId){
		GoodsSkuService goodsSkuService = (GoodsSkuService)SpringUtils.getBean("goodsSkuService");	//获取基本规格值服务对象
		BaseSkuValueService baseSkuValueService = (BaseSkuValueService)SpringUtils.getBean("baseSkuValueService");	//获取基本规格值服务对象
		
		//根据规格值，查找规格值对象数据
		BaseSkuValue baseSkuValue = baseSkuValueService.selectOneByName(freeTypeValue);
		
		//构建商品对应的规格值数据
		GoodsSku goodsSku = new GoodsSku();
		goodsSku.setName(baseSkuValue.getName());
		goodsSku.setGoodsId(goodsId);
		goodsSku.setBaseSkuId(baseSkuValue.getSkuId());
		goodsSku.setBaseSkuValueId(baseSkuValue.getId());
		goodsSku.setIsDelete("0");
		
		//查询商品对应的规格值数据是否存在
		GoodsSku goodsSkuOld = goodsSkuService.selectOneByParam(goodsSku);
		
		if(goodsSkuOld==null){
			goodsSku.setCreater("零售主管");
			goodsSku.setModifier("零售主管");
			goodsSku.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
			goodsSku.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
			
			goodsSkuService.insert(goodsSku);
		}else{
			goodsSku.setModifier("零售主管");
			goodsSku.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
			
			goodsSkuService.updateByPrimaryKey(goodsSku);
		}
	}	
	
	/**
	 * @Title: getTPlusGoodsStockByPay
	 * @Description 查询已经付款的商品对应的T+商品库存信息
	 * 返回信息：{"code":"EXSM0003","message":"提供令牌信息不正确"}
	 * @date 2017年5月27日上午08:08:35
	 * @author LeiJia  
	 */
	public void getTPlusGoodsStockByPay(){
		long start = System.currentTimeMillis();
		System.out.println(Common.printTimeStamp() + "将商城中支付成功的订单详情中的商品的库存从T+系统中读取并更新任务开始了。。。。");
		System.out.println("->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->");

		OpenAPI api = new OpenAPI(ConfigBeanAdapter.t_srvUrl,ConfigBeanAdapter.t_appKey,ConfigBeanAdapter.t_appSecret,ConfigBeanAdapter.t_user,ConfigBeanAdapter.t_pwd,ConfigBeanAdapter.t_account);
		//登录
		//System.out.println("开始登录！");
		//api.getTLogin();
		
		String method = "currentStock/Query";
		GoodsStockService goodsStockService = (GoodsStockService)SpringUtils.getBean("goodsStockService");	//获取商品库存服务对象
		String jsonstr = "";
		String data = "";
		try {
			//查询订单数据
			ParamMap paramMap = new ParamMap();
			paramMap.put("queryNoInventoryRevisedOrderStatus", Constants.TConstants.INVENTORY_REVISED_A);// 查询全部已付款订单未修改订单详情中商品库存的订单
	        List<Orders> orders =  orderService.selectList(paramMap);//不调用默认分页,调用自已的mapper中findUserPage
	        for(Orders order : orders){
	        	List<Products> products = order.getProducts();
	            for(Products product :products){
	            	System.out.println("商品名称："+product.getProductName());
			        data = "{param:{InventoryName:\""+product.getProductName()+"\",GroupInfo:{Warehouse:false,Inventory:true,InvProperty:true}}}";
	        		//获取库存数据
	        	    jsonstr = api.getData(method, data);
	        	    
	        		JSONArray jsonArray = JSONArray.parseArray(jsonstr);
					for(Object object : jsonArray){
						JSONObject jsonObject = (JSONObject)object;
						
						//构建商品库存数据对象
						GoodsStock goodsStock = new GoodsStock();
						goodsStock.setBaseQuantity(Integer.valueOf(jsonObject.getBigDecimal("ExistingQuantity").setScale(0,BigDecimal.ROUND_CEILING).toString()));
						
						//获取商品id
						String methodGoods = "inventory/Query";
						String dataGoods = "{param:{Code:\""+jsonObject.getString("InventoryCode")+"\",SelectFields:\"Id\"}}";
						//获取商品数据
						jsonstr = api.getData(methodGoods, dataGoods);
						JSONArray jsonArrayGoods = JSONArray.parseArray(jsonstr);
						if(jsonArrayGoods.size()>0){
							JSONObject jsonObjectGoods = (JSONObject)jsonArrayGoods.get(0);
							
							goodsStock.setGoodsId(jsonObjectGoods.getInteger("Id"));
						}
						
						//获取商品的库存规格（自由项）
						JSONArray jsonArrayFreeType = jsonObject.getJSONArray("DynamicPropertyKeys");
						JSONArray jsonArrayFreeTypeValue = jsonObject.getJSONArray("DynamicPropertyValues");
						for(Object objectFreeType : jsonArrayFreeType){
							String freeType = objectFreeType.toString();
							if("freeitem0".equals(freeType)){
								goodsStock.setFreeItem0(jsonArrayFreeTypeValue.get(0).toString());
								this.handleGoodsSku(jsonArrayFreeTypeValue.get(0).toString(), goodsStock.getGoodsId());
								continue;
							}
							if("freeitem1".equals(freeType)){
								goodsStock.setFreeItem1(jsonArrayFreeTypeValue.get(1).toString());
								this.handleGoodsSku(jsonArrayFreeTypeValue.get(1).toString(), goodsStock.getGoodsId());
								continue;
							}
							if("freeitem2".equals(freeType)){
								goodsStock.setFreeItem2(jsonArrayFreeTypeValue.get(2).toString());
								this.handleGoodsSku(jsonArrayFreeTypeValue.get(2).toString(), goodsStock.getGoodsId());
								continue;
							}
							if("freeitem3".equals(freeType)){
								goodsStock.setFreeItem3(jsonArrayFreeTypeValue.get(3).toString());
								this.handleGoodsSku(jsonArrayFreeTypeValue.get(3).toString(), goodsStock.getGoodsId());
								continue;
							}
						}
						int insertOrUpdate =0;
						//判断商品库存数据是否存在
						GoodsStock goodsStockOld = goodsStockService.selectOne(goodsStock);
						
						if(goodsStockOld==null){
							goodsStock.setCreateTime(DateUtil.formatYMDHMSToString(new Date()));
							goodsStock.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
							insertOrUpdate = goodsStockService.insert(goodsStock);
						}else{
							goodsStock.setId(goodsStockOld.getId());
							goodsStock.setModifyTime(DateUtil.formatYMDHMSToString(new Date()));
							insertOrUpdate = goodsStockService.updateByPrimaryKey(goodsStock);
						}
                      /*  if(insertOrUpdate > 0){  //由于不知道出库单什么时候创建暂时不标记订单中商品是否更新过库存
    						
    						//在订单详情中记录该商品是否更新过库存
    						OrderDetail detail = new OrderDetail();
    						detail.setProductId(product.getProductId());
    						detail.setOrderId(order.getOrderId());
    						detail.setGoods_sku_id(product.getGoods_sku_id());
    						detail.setGoods_sku_info(product.getGoods_sku_info());
    						detail.setInventory_revised(Constants.TConstants.INVENTORY_REVISED_B);
    					    orderService.updateOrderDetail(detail);
                        }*/
					}
	        	}
	        }
		} catch (Exception e) { 
			System.out.println(data);
			System.out.println(jsonstr);
		}		
		long end = System.currentTimeMillis();
		long hj = end - start;
		
		System.out.println("<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-");
		System.out.println(Common.printTimeStamp() + "将商城中支付成功的订单详情中的商品的库存从T+系统中读取并更新任务结束了。。。" + "共计用了：" + hj / 1000 + "秒");
	}
	

	/**
	 * @Title: addReceiptVoucher
	 * @Description 批量新增收款单
	 * @date 2017年06月16日下午16:38:35
	 * @author LeiJia  
	 */
	public void addReceiptVoucher(){
		long start = System.currentTimeMillis();
		System.out.println(Common.printTimeStamp() + "批量新增收款单任务开始了。。。。，开始中。。。");
		OpenAPI api = new OpenAPI(ConfigBeanAdapter.t_srvUrl,ConfigBeanAdapter.t_appKey,ConfigBeanAdapter.t_appSecret,ConfigBeanAdapter.t_user,ConfigBeanAdapter.t_pwd,ConfigBeanAdapter.t_account);
		//api.getTLogin();
		String method = "receiveVoucher/Create"; //T+新增收款单接口
		try{			
			//查询订单数据
			ParamMap paramMap = new ParamMap();
			paramMap.put("queryNoReceiptOrderStatus", Constants.TConstants.RECEIPT_PAYMENT_A);// 查询全部已付款订单未新增收款单的订单
	        List<Orders> orders =  orderService.selectList(paramMap);
	        for(Orders order : orders){
 	        	String  saleDeliveryCode = getSaleDeliveryCodeByOrderId(api,order.getOrderId());//查询T+销货单号
	        	if(Common.isEmpty(saleDeliveryCode)){
	        		continue;
	        	}

	        	OrderPayment payment = new OrderPayment();
	        	payment.setOrderId(order.getOrderId());
	        	List<OrderPayment> paymentList = orderService.selectByPayments(payment);
	        	String payCode ="";
	        	String bankAccount ="";
	        	String payType = paymentList.get(0).getPayType();//1:支付宝 2:微信 3:银联 4:畅捷通快捷支付，5.畅捷通微信支付，6：其它支付方式
	        	if(Common.isEmpty(payType)){
	        		continue;
	        	}
	    		if ("3".equals(payType) || "4".equals(payType)) {
	    			payCode = Constants.TConstants.SETTLE_STYLE_A;
	    			bankAccount ="建设银行中关村支行";
	    		} else if ("1".equals(payType)) {
	    			payCode = Constants.TConstants.SETTLE_STYLE_B;
	    			bankAccount ="建设银行中关村支行";
	    		} else if ("2".equals(payType)) {
	    			payCode = Constants.TConstants.SETTLE_STYLE_C;
	    			bankAccount ="建设银行中关村支行";
	    		}
	    		String data_="{dto:{ExternalCode:\""+order.getOrderId()+"\",VoucherDate:\""+DateUtil.dateToString2(new Date())+"\",Partner:{Code:\""+Constants.T_CUSTOMER_CODE+"\"},Currency:{Code:\"RMB\"},"
							+ "ExchangeRate:1.0000,"
							+ "Memo:\""+order.getMemo()+"\","
									+ "ArapMultiSettleDetails:[{SettleStyle:{Code:\"" + payCode + "\"},"
									+ "BankAccount:{Name:\""+bankAccount+"\"},"
									+ "OrigAmount:"+order.getTotalAmount()+"}],"
									+ "Details:[{VoucherCode:\""+saleDeliveryCode+"\","
									+ "VoucherType:{Code:\"SA04\"}}]}}";
	    		String jsonstr = api.getData(method, data_); 
	    		if(jsonstr.indexOf("ID") !=-1 && jsonstr.indexOf("Code") !=-1 && jsonstr.indexOf("Ts") !=-1){ //成功返回 [{"ID":125,"Code":"SK-2017-06-0002","Ts":"0000000000b633c1"}]
	    		   JSONArray jSONArray = JSON.parseArray(jsonstr);
	    		   if(jSONArray.size()>0){
	    			for(int i=0;i<jSONArray.size();i++){
		    			JSONObject job = jSONArray.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
		    			String receipt_payment_code = (String) job.get("Code");
		    			com.sc.dal.model.order.Order o = orderService.selectOrderByOrderId(order.getOrderId());
		    			o.setReceiptPayment(Constants.TConstants.RECEIPT_PAYMENT_B);
		    			o.setReceiptPaymentCode(receipt_payment_code);
		    			orderService.updateOrder(o);
	    			 }
	    			}
	    		}
	        }
			
		}catch(Exception e){
			e.printStackTrace();
		}
		//api.Logout(api.Access_Token);
		long end = System.currentTimeMillis();
		long hj = end - start;
		System.out.println(Common.printTimeStamp() + "批量新增收款单任务结束了。。。" + "共计用了：" + hj / 1000 + "秒");
	}
	
	//根据商城订单号查询T+系统中的销货订单号
	public String getSaleDeliveryCodeByOrderId(OpenAPI openAPI,String orderId){
		String saleDeliveryMethod = "saleDelivery/QueryExecuting"; //查询T+销售订单销货单号
    	String data = "{queryParam:[{WhereName:\"SaleDelivery.ExternalCode\",BeginValue:\""+orderId+"\"}]}";
    	try{
        	//销货单数据
    		String jsonstr = openAPI.getData(saleDeliveryMethod, data);
    		if(Common.isNotEmpty(jsonstr)){
            	JSONObject object = JSONObject.parseObject(jsonstr);
            	JSONArray jsonArraySaleDelivery =  (JSONArray) object.get("Rows");
        		if(jsonArraySaleDelivery !=null && jsonArraySaleDelivery.size()>0){
        			JSONObject jsonObjectSaleDelivery = (JSONObject)jsonArraySaleDelivery.get(0);					
        			//销货单号
        			return (String) jsonObjectSaleDelivery.get("saleDeliveryCode");
        		}
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return "";
	}
	
}
